package com.hqyj.javaGraduation.hotel.controller;

import com.hqyj.javaGraduation.config.PaySocketServer;
import com.hqyj.javaGraduation.hotel.pojo.UtMenuInfo;
import com.hqyj.javaGraduation.hotel.service.AliPayService;
import com.hqyj.javaGraduation.hotel.service.UtMenuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Controller
@RequestMapping("/ali")
public class AliPayController {

    @Autowired
    UtMenuInfoService utMenuInfoService;

    @Autowired(required = false)
    AliPayService service;

    //支付成功返回的页面
    @RequestMapping("/success")
    public String success(){
        return "success";
    }

    //访问alipay.html
    @RequestMapping("/alipay")
    public String alipay(){
        return "alipay";
    }

    //扫描支付
    @RequestMapping("/pay02")
    @ResponseBody
    public HashMap<String,Object> pay02(UtMenuInfo utMenuInfo){
        return service.aliPay02(utMenuInfo);
    }

    //表单支付提交处理页面
    @RequestMapping("/pay")
    public void pay(UtMenuInfo utMenuInfo, HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter pw = response.getWriter();
            pw.println(service.aliPay(utMenuInfo));
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //支付成功异步回调
    //注意：请求方式注解必须PostMapping，不支持GetMapping
    @PostMapping("/testJson")
    @ResponseBody
    public void test(HttpServletRequest request) throws IOException {

        //请求状态参数 trade_status，有两个值： 1  WAIT_BUYER_PAY 正在支付 2 TRADE_SUCCESS 支付成功
        System.out.println("支付状态："+ request.getParameter("trade_status"));
        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("发送信息给前端，提示支付完毕");
            PaySocketServer.sendMessage("ok");
        }

    }

}
